package com.example.demo;

/**
 * @Author lizhien (zhien.li@nascent.cn)
 * @Date 2020/8/4 19:51
 * @Version 1.0.0
 * @Description com.example.demo
 */

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import javax.jms.*;
import java.text.DateFormat;
import java.time.Instant;
import java.util.Date;
import java.util.concurrent.ExecutorService;

@Slf4j
public class MQProducer {

    public static void main(String[] args) throws Exception {

        ExecutorService cachedThreadPool = ThreadPool.getFixedThreadPool(1000);
        //ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("failover:(nio://localhost:61616)?randomize=true");
        Connection connection = ActiveMQPoolsUtil.getConnection();//connectionFactory.createConnection();

        Instant start = Instant.now();

        int i = 1;
        while (true) {
            int finalI = i;
            cachedThreadPool.execute(new Runnable() {
                @SneakyThrows
                @Override
                public void run() {
                    try {
                        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                        Destination destination = session.createQueue("hello.queue");
                        MessageProducer producer = session.createProducer(destination);
                        producer.setDeliveryMode(DeliveryMode.PERSISTENT);
                        producer.send(session.createTextMessage(DateFormat.getDateTimeInstance().format(new Date()) + " 生产者的消息数据------编号---" + finalI + "---Now Thread: " + Thread.currentThread().getName()));
                        producer.close();
                        session.close();
//                    log.info(DateFormat.getDateTimeInstance().format(new Date()) + "---生产者的消息数据---编号-" + finalI + "---线程ID-" + Thread.currentThread().getId()
//                        + "---线程名称-" + Thread.currentThread().getName() + "---耗时-" + Duration.between(start, Instant.now()).getSeconds() + "秒");
                    } catch (Exception e) {e.printStackTrace();}
                }
            });
//            log.info(DateFormat.getDateTimeInstance().format(new Date()) + "---开始循环---" + i);
            i++;
            if (i > 10000) {
                Thread.sleep(200000);
                connection.close();
                break;
            }
        }
    }

}
